package cn.com.clearbus.mini.controller;

import cn.com.clearbus.mini.entity.MiniFile;
import cn.com.clearbus.mini.service.IFileService;
import cn.com.clearbus.result.DynamicResult;
import cn.com.clearbus.result.ErrCode;
import io.swagger.annotations.ApiOperation;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;



@RestController
@RequestMapping(value = "/file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    IFileService fileService;



    @PostMapping("/upload")
    @ApiOperation(value = "文件上传", notes = "时间：2019-10-16 作者: 刘王震")
    public DynamicResult upload(MultipartFile file) {
        log.info(file.getName());
        log.info(file.getOriginalFilename());
        log.info(String.valueOf(file.getSize()));
        String folder = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\";
        File localFile = new File(folder, System.currentTimeMillis() + ".txt");

        MiniFile miniFile = new MiniFile();
        miniFile.setFileName(file.getName()).setOriginName(file.getOriginalFilename())
                .setFileUrl(localFile.getAbsolutePath()).setCreateTime(LocalDateTime.now());
        try {
            file.transferTo(localFile);
            return fileService.uploadFileInfo(miniFile);
        } catch (IOException e) {
            log.error(e.getMessage());
            return  new DynamicResult(ErrCode.FAILURE,"文件上传失败");
        }

    }

    @GetMapping("/download/{id}")
    @ApiOperation(value = "文件下载", notes = "时间：2019-10-16 作者: 刘王震")
    public DynamicResult download(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
        String folder = System.getProperty("user.dir") + "\\clearbus-wxjava-miniapp\\src\\main\\resources\\static\\";
        File file = new File(folder, id + ".txt");
        if (!file.exists()) {
            return new DynamicResult(ErrCode.FAILURE,"文件不存在");
        }
        try (
            InputStream ips = new FileInputStream(file);
            OutputStream ops = response.getOutputStream();) {
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=test.txt");
            IOUtils.copy(ips, ops);
            ops.flush();
            return new DynamicResult(ErrCode.SUCCESS,"下载成功");
        }catch (IOException e){
            log.error("文件下載出現問題,原因是:{}",e.getMessage());
            return  new DynamicResult(ErrCode.FAILURE,"下载失败");
        }
    }
}
